﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Appkiz.Apps.Workflow.Library;
using Tiger.Common;
using Tiger.Models;
using Appkiz.Library.Notification;
using Appkiz.Library.Common;
using Appkiz.Library.Security.Authentication;
using Hangfire;
using Hangfire.Storage;
using Appkiz.Apps.Calendar.Models.Data;

namespace DQC.Controllers
{
    public class NotificationController : Controller
    {
        private static NotificationMgr notifyMgr = new NotificationMgr();
        private CalendarEntities calendarEntities = new CalendarEntities();

        // 流程管理
        WorkflowMgr wkfMgr = new WorkflowMgr();

        #region 发送提交通知
        public ActionResult SendSubmitNotification()
        {
            /*
             * 参数获取
             */
            // 流程ID
            var MessageID = Request.Params["MessageID"];
            // 用户ID
            var UserID = Request.Params["UserID"];
            // 节点ID
            var NodeKey = Request.Params["NodeKey"];

            /*
             * 参数校验
             */
            // 流程ID
            if (string.IsNullOrEmpty(MessageID))
            {
                return new JsonNetResult(new
                {
                    Succeed = false,
                    Message = "流程ID不能为空"
                });
            }
            // 用户ID
            if (string.IsNullOrEmpty(UserID))
            {
                return new JsonNetResult(new
                {
                    Succeed = false,
                    Message = "用户ID不能为空"
                });
            }
            // 节点ID
            if (string.IsNullOrEmpty(NodeKey))
            {
                return new JsonNetResult(new
                {
                    Succeed = false,
                    Message = "节点ID不能为空"
                });
            }

            /*
             * 发送极光通知
             */
            // 发送极光提醒
            // 根据消息ID获得对应的标题
            Message message = wkfMgr.GetMessage(MessageID);
            if (message == null)
            {
                return new JsonNetResult(new
                {
                    Succeed = false,
                    Message = "消息不存在"
                });
            }
            else
            {
                // 发送系统通知
                WorkflowUtil.SendNotification(MessageID, NodeKey, UserID);

                // 发送极光推送消息
                Dictionary<string, object> dict = new Dictionary<string, object>();

                dict["type"] = WHConstants.JPush_Workflow_Type;
                dict["title"] = string.Format("您有新的流程提醒通知 \"{0}\"", message.MessageTitle);
                dict["content"] = new Dictionary<string, object>()
                        {
                            {"mid",  MessageID}
                        };
                WorkflowUtil.SendJPushNotification(new List<object>() { UserID }, dict);

                return new JsonNetResult(new
                {
                    Succeed = true,
                    Message = "提醒发送成功"
                });
            }
        }
        #endregion

        #region 添加/更新提醒
        public ActionResult AddOrUpdateRemind()
        {
            try
            {
                /*
				 * 参数获取
				 */
                // 任务ID
                var RemindID = Request.Params["ID"];

                /*
				 * 参数校验
				 */
                // 任务ID
                if (string.IsNullOrEmpty(RemindID))
                {
                    return new JsonNetResult(new
                    {
                        Succeed = false,
                        Message = "任务ID不存在"
                    });
                }

                CLD_Remind remind = calendarEntities.CLD_Remind.Where(n => n.ID.ToString() == RemindID).FirstOrDefault();
                if (remind == null)
                {
                    return new JsonNetResult(new
                    {
                        Succeed = false,
                        Message = "提醒不存在"
                    });
                }
                else
                {
                    /*
                     * 更新定时任务
                     */
                    // 任务ID
                    var TaskID = remind.TaskID.ToString();

                    TimeSpan span = remind.RemindTime.Subtract(DateTime.Now);
                    // 检查该提醒任务是否已经再数据库中
                    using (var defaultDb = new WhDbContext())
                    {
                        var calendarTask = defaultDb.CalendarTask.Where(n => n.TaskID == TaskID).FirstOrDefault();
                        // 任务不存在，则添加该任务
                        if (calendarTask == null)
                        {

                            calendarTask = new TGR_CalendarTask();
                            var jobId = BackgroundJob.Schedule(() => WorkflowUtil.SendCalendarNotification(TaskID), span);
                            calendarTask.JobID = jobId;
                            calendarTask.TaskID = remind.TaskID.ToString();
                            defaultDb.CalendarTask.Add(calendarTask);
                        }
                        else
                        {
                            BackgroundJob.Delete(calendarTask.JobID);
                            var jobId = BackgroundJob.Schedule(() => WorkflowUtil.SendCalendarNotification(TaskID), span);
                            calendarTask.JobID = jobId;
                        }

                        defaultDb.SaveChanges();

                        return new JsonNetResult(new
                        {
                            Succeed = true,
                            Message = "提醒设置成功"
                        });
                    }
                }
            }
            catch (Exception e)
            {
                LogService.WriteLog("Tiger", "Message:" + e.Message, "_Debug", LogService.LogLevel.Debug);
                return new JsonNetResult(new
                {
                    Succeed = false,
                    Message = e.Message
                });
            }
        }
        #endregion

        #region 删除提醒
        public ActionResult DeleteRemind()
        {
            try
            {
                /*
				 * 参数获取
				 */
                // 任务ID
                var TaskID = Request.Params["ID"];

                /*
				 * 参数校验
				 */
                // 任务ID
                if (string.IsNullOrEmpty(TaskID))
                {
                    return new JsonNetResult(new
                    {
                        Succeed = false,
                        Message = " 提醒ID不存在"
                    });
                }

                /*
                 * 检查是否存在该定时任务
                 */
                using (var db = new WhDbContext())
                {
                    var calendarTask = db.CalendarTask.Where(n => n.TaskID == TaskID).FirstOrDefault();
                    if (calendarTask == null)
                    {
                        return new JsonNetResult(new
                        {
                            Succeed = false,
                            Message = "任务不存在"
                        });
                    }
                    else
                    {
                        // 删除该任务
                        BackgroundJob.Delete(calendarTask.JobID);
                        db.CalendarTask.Remove(calendarTask);
                        db.SaveChanges();

                        return new JsonNetResult(new
                        {
                            Succeed = true,
                            Message = "提醒取消成功"
                        });
                    }
                }

            }
            catch (Exception e)
            {
                LogService.WriteLog("Tiger", "Message:" + e.Message, "_Debug", LogService.LogLevel.Debug);
                return new JsonNetResult(new
                {
                    Succeed = false,
                    Message = e.Message
                });
            }
        }
        #endregion
    }
}